<template>
  <div ref="echartsRef" class="echarts-container"></div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, nextTick, watch, ref } from 'vue';
import * as echarts from 'echarts';
import type { ECharts, PieSeriesOption } from 'echarts';

interface EchartsDataItem {
  name: string;
  value: number;
  itemStyle: {
    color: string;
  };
  clickData?: any;
}

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  echartsData: {
    type: Array as PropType<EchartsDataItem[]>,
    default: () => []
  },
  value: {
    type: Number,
    default: 0
  }
});
const emit = defineEmits<{
  (e: 'clickData', params: any): void;
}>();

const echartsRef = ref<HTMLElement | null>(null);
const myChart = ref<ECharts | null>(null);
const resizeObserver = ref<ResizeObserver | null>(null);

// 初始化图表
const initChart = () => {
  if (!echartsRef.value) return;

  myChart.value = echarts.init(echartsRef.value);
  setupResizeObserver();
  updateChart();
};

// 更新图表数据
const updateChart = () => {
  if (!myChart.value || !props.echartsData?.length) return;

  const { colors, seriesData, sum } = processChartData(props.echartsData);

  const option: echarts.EChartsOption = {
    color: colors,
    title: getPieTitleConfig(props.value),
    tooltip: getTooltipConfig(sum),
    legend: getLegendConfig(),
    series: [getPieSeriesConfig(props.title, seriesData)]
  };

  myChart.value.setOption(option);
  setupChartEvents();
};

// 处理图表数据
const processChartData = (data: EchartsDataItem[]) => {
  const colors: string[] = [];
  const seriesData: { name: string; value: number; effective?: string | number }[] = [];
  let sum = 0;

  data.forEach((item, index) => {
    colors.push(item.itemStyle.color);
    seriesData.push({
      name: item.name,
      value: item.value,
      effective: item.clickData && item.clickData[index]?.effective
    });
    sum += Number(item.value);
  });

  return { colors, seriesData, sum };
};

// 图表配置项
const getPieTitleConfig = (value: number) => ({
  show: true,
  text: '报警总数',
  subtext: String(value || 0),
  left: 'center',
  top: '42%',
  textStyle: {
    color: '#fff',
    fontSize: 14,
    fontWeight: 400
  },
  subtextStyle: {
    color: '#00FFFF',
    fontSize: 12,
    fontWeight: 700,
    fontFamily: 'PangMenZhengDao'
  }
});

const getTooltipConfig = (sum: number) => ({
  position: [50, 50] as [number, number],
  formatter: (params: any) => {
    const percentage = sum !== 0 ? (Number(params.value) / sum) * 100 : 0;
    return `
      ${params.seriesName}<br/>
      <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>
      ${params.name}占比:${percentage.toFixed(2)}%<br/>
    `;
  }
});

const getLegendConfig = () => ({
  orient: 'horizontal' as const,
  left: 'center',
  bottom: '0',
  itemGap: 10,
  itemWidth: 10,
  itemHeight: 10,
  textStyle: {
    color: '#fff',
    fontSize: 13
  }
});

const getPieSeriesConfig = (name: string, data: any[]): PieSeriesOption => ({
  name,
  type: 'pie',
  radius: ['50%', '70%'],
  center: ['50%', '50%'],
  label: {
    show: false,
    formatter: '{c}',
    fontSize: 13
  },
  data
});

// 设置图表事件
const setupChartEvents = () => {
  if (!myChart.value) return;

  myChart.value.off('click');
  myChart.value.on('click', (params: any) => {
    emit('clickData', params);
  });
};

// 设置响应式观察
const setupResizeObserver = () => {
  if (!echartsRef.value || !myChart.value) return;

  resizeObserver.value = new ResizeObserver(() => {
    myChart.value?.resize();
  });

  resizeObserver.value.observe(echartsRef.value);
};

// 清理资源
const cleanup = () => {
  if (resizeObserver.value) {
    resizeObserver.value.disconnect();
    resizeObserver.value = null;
  }

  if (myChart.value) {
    myChart.value.dispose();
    myChart.value = null;
  }

  window.removeEventListener('resize', handleResize);
};

const handleResize = () => {
  myChart.value?.resize();
};

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    initChart();
  });
  window.addEventListener('resize', handleResize);
});

onUnmounted(cleanup);

// 监听数据变化
watch(
  () => [props.echartsData, props.value],
  (newVal) => {
    updateChart();
  },
  { deep: true }
);
</script>

<style scoped>
.echarts-container {
  width: 100%;
  height: 100%;
}
</style>
